<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
      转化思路：
      设定背包为所有重量的一半，装满闭包的最大价值即装满石头的重量。然后用总和-2*最大重量即可
      
      */
      var lastStoneWeightII = function (stones) {
        stones.sort((a, b) => a - b)
        let sum = stones.reduce((pre, item) => (pre += item), 0)
        let bagSize = parseInt(sum / 2)
        let dp = new Array(bagSize + 1).fill(0)
        for (let i = 0; i < stones.length; i++) {
          for (let j = bagSize; j >= stones[i]; j--) {
            dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i])
          }
        }
        return sum - 2 * dp[bagSize]
      }
    </script>
  </body>
</html>
